
const id = $.getUrlParam('id');

let zTree;

// zTree 配置
var zTreeSetting = {
    async: {
        enable: true,
        url: "/assignee/getSubNodesByDeptId",
        type: "get",
        autoParam: ["id=deptId"],
        otherParam: {"userName": ""}
    }
};

//当前点击的办理人
let assignee;

$(function () {

    //回显
    //获取流程数据
    $.ajax({
        type: "GET",
        url: "/flowDef/getById",
        contentType: "application/x-www-form-urlencoded",
        dataType: "json",
        data: {"id": id},
        success: function (data) {
            if (data.code === SUCCESS_CODE) {
                //console.log(data);

                let flowDefDto = data.payload;
                let flowDefEntity = flowDefDto.flowDefEntity;

                $('.flow-and-task [name="flowDefName"]').val(flowDefEntity.name);
                $('.flow-and-task [name="flowDefDes"]').val(flowDefEntity.des);

                let flowDefTaskEntityList = flowDefDto.flowDefTaskEntityList;
                $.each(flowDefTaskEntityList, function () {
                    let flowDefTaskEntity = this;
                    let taskType = flowDefTaskEntity.type;
                    if (taskType === 'start' || taskType === 'end') {
                        return true;//相当于continue，return false 相当于break
                    }

                    let taskNode = $('#taskTemplate [taskType="' + taskType + '"]');
                    let taskNodeClone = taskNode.clone(true);
                    taskNodeClone.find('[name="name"]').val(flowDefTaskEntity.name);
                    taskNodeClone.find('[name="des"]').val(flowDefTaskEntity.des);
                    if (taskType != 'pointTask') {
                        taskNodeClone.find('[name="assignees"]').val(flowDefTaskEntity.assigneesName);
                        taskNodeClone.find('[name="assignees"]').data('userIdArray', flowDefTaskEntity.assignees.split(','));
                    }

                    $('.flow [taskType="end"]').before(taskNodeClone);
                });

            } else {
                toastr.error(data.msg);
            }
        }
    });

    //是否正在拖拽
    let dragging = false;

    //是否已经移动到 flow 区域内
    let comeInFlow = false;

    //鼠标位置
    let cursorLeft = 0;
    let cursorTop = 0;

    //纵向滚动条滚动事件
    $(window).scroll(function () {
        $('.flow-and-task').css('margin-top', $(document).scrollTop());
    });

    //监听鼠标移动事件
    $(document).mousemove(function (e) {

        cursorLeft = e.clientX;
        cursorTop = e.clientY + $(document).scrollTop();

        // flow 的位置
        let flowTop = $('.flow [taskType="start"]').offset().top + $(document).scrollTop();
        let flowBottom = $('.flow [taskType="end"]').offset().top + $(document).scrollTop();
        let flowLeft = $('.flow').offset().left;
        let flowRight = flowLeft + $('.flow').width();

        //console.log(flowTop + ";" + cursorTop + ";" + flowBottom);

        //拖拽到 flow 区域
        if (cursorTop > flowTop && cursorTop < flowBottom &&
            cursorLeft > flowLeft && cursorLeft < flowRight &&
            dragging) {
            comeInFlow = true;
        } else {
            comeInFlow = false;
        }
    });

    //监听拖拽事件
    $(".draggable").draggable({
        opacity: 0.7,
        helper: "clone",
        start: function () {
            dragging = true;
        },
        drag: function () {
        },
        stop: function () {
            //获取taskType
            let taskType = $(this).parent().parent().attr('taskType');
            let taskNode = $('#taskTemplate [taskType="' + taskType + '"]')

            if (comeInFlow) {
                //获取释放位置
                $('.flow .task').each(function () {
                    let flowTop = $(this).find('.task-node').children(":first").offset()
                        .top;
                    if (cursorTop < flowTop) {
                        $(this).before(taskNode.clone(true));
                        return false;
                    }
                });
            }

            dragging = false;
            comeInFlow = false;
        }
    });

    //办理人
    $('.task-property [name="assignees"]').click(function () {
        assignee = $(this).parent().parent().parent().parent().parent();

        var taskType = assignee.attr('taskType');
        if (taskType == 'task') {
            zTreeSetting.check = {
                enable: true,
                chkStyle: "radio",
                radioType: "all"
            };

        } else {
            zTreeSetting.check = {
                enable: true
            };
        }

        openModal();
    });

    //搜索
    $('.search button').click(function () {
        let search = $(this).parent().find('input').val();
        zTreeSetting.async.otherParam.userName = search;
        getAssignee();
        //阻止默认事件
        return false;
    });

    //选择办理人
    $('#select').click(function () {
        var nodes = zTree.getCheckedNodes(true);
        var userIdArray = [];
        var userNameArray = [];
        $.each(nodes, function () {
            let node = this;
            if (node.isUser) {
                userIdArray.push(node.id);
                userNameArray.push(node.name);
            }
        });
        assignee.find('[name="assignees"]').data('userIdArray', userIdArray);
        assignee.find('[name="assignees"]').val(userNameArray.join(','));
        $('#assignee').modal('toggle');
    });

    //保存工作流
    $('.flow .save').click(function () {

        let flowDefDto = new Object();

        //判断是否添加了节点
        if ($('.flow .task').length <= 2) {
            toastr.warning("请添加流程节点");
            return;
        }

        //流程信息
        let flowDefName = $('.flow-def-info [name="flowDefName"]').val();
        let flowDefDes = $('.flow-def-info [name="flowDefDes"]').val();
        if ($.isEmptyObject(flowDefName)) {
            toastr.warning("流程名称不能为空");
            return;
        }

        flowDefDto.flowDefEntity = {"id": id, "name": flowDefName, "des": flowDefDes};

        let flowArray = [];
        let orderNum = 0;
        let checkPass = true;

        $('.flow .task').each(function () {
            let flowObj = new Object();
            let type = $(this).attr('taskType');
            orderNum++;
            flowObj.type = type;
            flowObj.orderNum = orderNum;
            if (type == 'start') {
                flowObj.name = '开始';
            } else if (type == 'end') {
                flowObj.name = '结束';
            } else {
                flowObj.des = $(this).find('[name="des"]').val();
                let name = $(this).find('[name="name"]').val();
                //let assigneesName = $(this).find('[name="assignees"]').val();
                let assigneesIds = $(this).find('[name="assignees"]').data('userIdArray');

                //校验名称不能为空
                if ($.isEmptyObject(name)) {
                    toastr.warning('任务名称不能为空');
                    checkPass = false;
                    return false;
                }

                if (type != 'pointTask' && $.isEmptyObject(assigneesIds)) {
                    //校验办理人不能为空
                    toastr.warning('任务办理人不能为空');
                    checkPass = false;
                    return false;
                }

                flowObj.name = name;
                if (type != 'pointTask') {
                    flowObj.assignees = assigneesIds.join(',');
                }
            }

            flowArray.push(flowObj);
        });

        if (checkPass) {
            flowDefDto.flowDefTaskEntityList = flowArray;
            //console.log(flowDefDto);
            $.ajax({
                type: "POST",
                url: "/flowDef/modifyFlowDef",
                contentType: "application/json",
                dataType: "json",
                data: JSON.stringify(flowDefDto),
                success: function (data) {
                    if (data.code === SUCCESS_CODE) {
                        toastr.success(data.msg);
                        setTimeout(function () {
                            goto("/admin/workflow/flow_list.html");
                        }, 2000);
                    } else {
                        toastr.error(data.msg);
                    }
                }
            });
        }
    });

    //移除节点
    $('.task-property .remove').click(function () {
        $(this).parent().parent().parent().parent().remove();
    });
});


/**
 * 打开模态框，选择办理人
 */
function openModal() {
    $('#assignee').modal('toggle');
    getAssignee();
}

function getAssignee() {
    zTree = $.fn.zTree.init($("#assigneeTree"), zTreeSetting);
}
